package org.summerframework.component.security.spring.exception;

import org.summerframework.component.security.core.SecurityResultCode;
import org.summerframework.component.security.core.config.LoginProperties;
import org.summerframework.core.base.result.ResultCode;
import org.summerframework.core.base.result.ResultDTO;
import org.summerframework.web.exception.resolver.ExceptionResolveHandler;
import org.springframework.security.core.AuthenticationException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author 石超
 * @version v1.0.0
 */
public class NotLoginAuthenticationExceptionResolveHandler implements ExceptionResolveHandler {
    private LoginProperties loginProperties;

    public NotLoginAuthenticationExceptionResolveHandler(LoginProperties loginProperties) {
        this.loginProperties = loginProperties;
    }

    @Override
    public ResultCode resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        return SecurityResultCode.ERROR_NOT_LOGIN;
    }

    @Override
    public boolean supper(Exception ex) {
        return ex instanceof AuthenticationException;
    }

    @Override
    public ModelAndView determineModelAndView(HttpServletRequest request, ResultDTO resultDTO, boolean isHtml, Exception e) {
        return isHtml ? new ModelAndView(new RedirectView(loginProperties.redirectLogin(request))) : null;
    }
}
